package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //直接使用baseMapper
        //所有子菜单
        List<CategoryEntity> all = baseMapper.selectList(null);

        //查询一级子菜单
        List<CategoryEntity> list = all.stream().filter(
                categoryEntity -> categoryEntity.getParentCid() == 0
        ).map(menu ->{
                    menu.setChildrens(getChildrens(menu,all));
                    return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        //构造树形子菜单

        return list;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1. 检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    //修改页面  分类 级联 查找id全路径
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        ArrayList<Long> list = new ArrayList<>();
        CategoryEntity categoryEntity = this.getById(catelogId);

        List<Long> parentPath = findCateLog(catelogId, list);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }


    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    //更新分类数据时，也要更新引用分类数据表的数据
    @Override
    @Transactional
//    @Caching(evict = {
//            @CacheEvict(value = "categorys",key = "'getLevel1Categorys'" ),
//            @CacheEvict(value="categorys",key = "'getCatalogJson'")
//
//    })
    @CacheEvict(value = "categorys",allEntries = true)
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);

        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    //查询一级菜单
    @Cacheable(value = {"categorys"},key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys查询中   ---");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));

        return categoryEntities;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;
    //查询所有的菜单


    @Cacheable(value = "categorys",key = "#root.method.name")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        System.out.println("从数据库查");
        //优化 数据库多次查询  改为一次查询
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        List<CategoryEntity> level1Categorys = getParent_cid(selectList,0L);
        Map<String, List<Catelog2Vo>> json = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

            List<CategoryEntity> category2Entries = getParent_cid(selectList,v.getCatId());
            List<Catelog2Vo> catelog2vos = null;
            if (category2Entries != null) {
                catelog2vos = category2Entries.stream().map(item -> {

                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());

                    //给二级分类找三级分类
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList,item.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catalog3Vo> catalog3Vos = level3Catelog.stream().map(l3 -> {
                            Catelog2Vo.Catalog3Vo catalog3Vo = new Catelog2Vo.Catalog3Vo(item.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;

                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catalog3Vos);

                    }
                    return catelog2Vo;

                }).collect(Collectors.toList());
            }
            return catelog2vos;
        }));

        return json;
    }
    //todo 产生堆外内存溢出

    public Map<String, List<Catelog2Vo>> getCatalogJson2(){
        String catalogJson = redisTemplate.opsForValue().get("CatalogJson");

        if(StringUtils.isEmpty(catalogJson)){
            System.out.println("缓存不命中，查询数据库");
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbwithRedisLock();
          return catalogJsonFromDb;
        }
        System.out.println("缓存命中，直接返回");
        Map<String, List<Catelog2Vo>> stringListMap = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return stringListMap;

    }

    @Autowired
    private RedissonClient redissonClient;
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbwithRedisLock() {

        //1.占分布式锁
        RLock catalogJsonLock = redissonClient.getLock("catalogJsonLock");

        Map<String, List<Catelog2Vo>> cataJsonFromDb;
          catalogJsonLock.lock();
            try{
                cataJsonFromDb = getCataJsonFromDb();
            }finally {
                //删除key，可以让其他线程set成功
                //为了删除自己锁，获取值对比和删除是原子操作
                catalogJsonLock.unlock();

            }
        return cataJsonFromDb;

    }

    public Map<String, List<Catelog2Vo>>  getCataJsonFromDb(){
        String catalogJson = redisTemplate.opsForValue().get("CatalogJson");
        if(StringUtils.isNotEmpty(catalogJson)){
            Map<String, List<Catelog2Vo>> stringListMap = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return stringListMap;
        }
        System.out.println("从数据库查");
        //优化 数据库多次查询  改为一次查询
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        List<CategoryEntity> level1Categorys = getParent_cid(selectList,0L);
        Map<String, List<Catelog2Vo>> json = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

            List<CategoryEntity> category2Entries = getParent_cid(selectList,v.getCatId());
            List<Catelog2Vo> catelog2vos = null;
            if (category2Entries != null) {
                catelog2vos = category2Entries.stream().map(item -> {

                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());

                    //给二级分类找三级分类
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList,item.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catalog3Vo> catalog3Vos = level3Catelog.stream().map(l3 -> {
                            Catelog2Vo.Catalog3Vo catalog3Vo = new Catelog2Vo.Catalog3Vo(item.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;

                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catalog3Vos);

                    }
                    return catelog2Vo;

                }).collect(Collectors.toList());
            }
            return catelog2vos;
        }));

        try{
            Thread.sleep(2000);
        }catch (Exception e){

        }

        //返回结果时，要加入缓存
        String s = JSON.toJSONString(json);

        redisTemplate.opsForValue().set("CatalogJson",s);
        return json;
    }
//本地服务锁
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbwithLock() {
        synchronized (this){
            String catalogJson = redisTemplate.opsForValue().get("CatalogJson");
           if(StringUtils.isNotEmpty(catalogJson)){
               Map<String, List<Catelog2Vo>> stringListMap = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
               });
               return stringListMap;
           }
            System.out.println("从数据库查");
            //优化 数据库多次查询  改为一次查询
            List<CategoryEntity> selectList = baseMapper.selectList(null);

            List<CategoryEntity> level1Categorys = getParent_cid(selectList,0L);
            Map<String, List<Catelog2Vo>> json = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

                List<CategoryEntity> category2Entries = getParent_cid(selectList,v.getCatId());
                List<Catelog2Vo> catelog2vos = null;
                if (category2Entries != null) {
                    catelog2vos = category2Entries.stream().map(item -> {

                        Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());

                        //给二级分类找三级分类
                        List<CategoryEntity> level3Catelog = getParent_cid(selectList,item.getCatId());
                        if (level3Catelog != null) {
                            List<Catelog2Vo.Catalog3Vo> catalog3Vos = level3Catelog.stream().map(l3 -> {
                                Catelog2Vo.Catalog3Vo catalog3Vo = new Catelog2Vo.Catalog3Vo(item.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                return catalog3Vo;

                            }).collect(Collectors.toList());
                            catelog2Vo.setCatalog3List(catalog3Vos);

                        }
                        return catelog2Vo;

                    }).collect(Collectors.toList());
                }
                return catelog2vos;
            }));

            try{
                Thread.sleep(2000);
            }catch (Exception e){

            }

            //返回结果时，要加入缓存
            String s = JSON.toJSONString(json);

            redisTemplate.opsForValue().set("CatalogJson",s);
            return json;
        }

    }

    private List<CategoryEntity> getParent_cid( List<CategoryEntity>  selectList,Long parent_cid) {
       // return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

    public List<Long> findCateLog(Long category,List<Long> list){
        list.add(category);
        CategoryEntity categoryEntity = this.getById(category);

        if(categoryEntity.getParentCid()!=0){
            findCateLog(categoryEntity.getParentCid(),list);
        }

        return list;
    }
    //递归查询子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity menu, List<CategoryEntity> all) {
       //查询当前菜单的子菜单
        List<CategoryEntity> childrens = all.stream().filter(categoryEntity ->
            categoryEntity.getParentCid().longValue()== menu.getCatId().longValue()
        ).map(categoryEntity->{
            //查询子菜单的子菜单
            categoryEntity.setChildrens(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return childrens;
    }


}